package org.starsource.forum.client.view;

import java.util.List;

import org.starsource.forum.client.domain.ResourceObject;
import org.starsource.forum.client.widget.ImagePanel;
import org.starsource.forum.client.widget.handler.ImageClickHandler;
import org.starsource.forum.shared.util.ImageContainerSupport;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.VerticalPanel;

public class ImageList extends FlowPanel {

	private final Image slide = new Image();
	private final DialogBox dialogBox = new DialogBox();

	private ImageClickHandler imageClickHandler = new ImageClickHandler() {

		@Override
		public void onImageClick(String url, int width, int height) {
			slide.setUrl(url);

			ImageContainerSupport ratio = new ImageContainerSupport(width, height,
					Window.getClientWidth() - 30, Window.getClientHeight() - 40);
			ratio.calculateScale();
//			Window.alert("IMAGE("+ratio.getImageWidth()+","+ratio.getImageHeight()+ ") " +
//					"CONTAINER(" + ratio.getContainerWidth() + "," + ratio.getContainerHeight() + ") " +
//					"SCALE(" + ratio.getScaleWidth() + "," + ratio.getScaleHeight() + ")");
			slide.setWidth(ratio.getScaleWidth() + "px");
			slide.setHeight(ratio.getScaleHeight() + "px");

			slide.addClickHandler(new ClickHandler() {

				@Override
				public void onClick(ClickEvent event) {
					dialogBox.hide();
				}

			});
			dialogBox.setAutoHideEnabled(true);
			dialogBox.setAnimationEnabled(true);
			dialogBox.setGlassEnabled(true);

			dialogBox.setWidget(slide);
			dialogBox.center();
		}

	};

	public void setImageList(List<ResourceObject> imageList) {
		  for(int index = 0; index < imageList.size(); index ++) {
			  VerticalPanel vPanel = new VerticalPanel();
			  vPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
			  vPanel.addStyleName("displayInline");

			  ImagePanel imagePanel = new ImagePanel(
					  170, 170,
					  imageList.get(index).getWidth(), imageList.get(index).getHeight(),
					  "filedownload?resourceId=" +  imageList.get(index).getId() + "&thumbnail=false",
					  "filedownload?resourceId=" +  imageList.get(index).getId() + "&thumbnail=true");
//			  StringUtil.formatLength(imageList.get(index).getUrl(),20)
			  imagePanel.setImageClickHandler(imageClickHandler);
			  imagePanel.setStylePrimaryName("gwter-DecoratorPanel-180");
			  vPanel.add(imagePanel);

			  Anchor link = new Anchor(imageList.get(index).getUrl());
			  link.setHref("filedownload?resourceId=" +  imageList.get(index).getId() + "&thumbnail=false");
			  vPanel.add(link);
			  this.add(vPanel);
		  }
	  }
}
